package com.hangzhou.xyj.ui.adapter;

import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.SeekBar;
import android.widget.TextView;

import com.hangzhou.xyj.R;
import com.hangzhou.xyj.XYJApplication;
import com.hangzhou.xyj.db.RecordDao;
import com.hangzhou.xyj.manager.IntentManager;
import com.hangzhou.xyj.model.RecordModel;
import com.hangzhou.xyj.ui.dialog.TipsDialog;
import com.hangzhou.xyj.ui.widget.CircleImageView;
import com.hangzhou.xyj.ui.widget.multiimageselector.utils.TimeUtils;
import com.hangzhou.xyj.ui.widget.views.MyTextView;
import com.hangzhou.xyj.utils.ToastUtil;
import com.mediaideas.videoengine.utils.MusicUtils;

import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by DT-038 on 2016/1/6.
 * 我的录音Adapter
 */
public class MyRecordAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {

    OnPlayBackListener onPlayBackListener;
    OnItemClickListener onItemClickListener;
    private Context mContext;
    private LayoutInflater mLayoutInflater;
    private List<RecordModel> mData;
    private RecordDao dao = new RecordDao(mContext);
    private PlayStatus PLAY_STATUS = PlayStatus.PAUSE;//初始化为停止状态

    public MyRecordAdapter(Context context, List<RecordModel> data) {
        this.mContext = context;
        if (data == null) {
            data = new ArrayList<>();
        }
        this.mData = data;
        mLayoutInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    }

    /**
     * 设置播放状态
     *
     * @param
     * @return
     * @author yaohuix
     * @date 2016/5/18 12:01
     */
    public void setPlayStatus(View view, PlayStatus status) {
        PLAY_STATUS = status;
        changePlayState(view, status);
    }

    public void setOnStartPlayBackListener(OnPlayBackListener listener) {
        this.onPlayBackListener = listener;
    }

    public void setOnItemClickListener(OnItemClickListener listener) {
        this.onItemClickListener = listener;
    }

    private void changePlayState(View view, PlayStatus playStatus) {
        if (!(view instanceof ImageView)) {
            return;
        }
        switch (playStatus) {
            case PLAYING://正在播放
                PLAY_STATUS = PlayStatus.PLAYING;
                ((ImageView) view).setImageResource(R.drawable.ic_pause_transparent);
                break;
            case PAUSE://其他
                PLAY_STATUS = PlayStatus.PAUSE;
                ((ImageView) view).setImageResource(R.drawable.ic_play_transparent);
                break;
        }
    }

    public void update(List<RecordModel> list) {
        if (list == null) {
            list = new ArrayList<>();
        }
        this.mData = list;
        notifyDataSetChanged();
    }

    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup viewGroup, int viewType) {
        RecyclerView.ViewHolder viewHolder;
        switch (viewType) {
            default:
                viewHolder = new RecordViewHolder(mLayoutInflater.inflate(R.layout.layout_myrecord_item, viewGroup, false));
                break;
        }
        return viewHolder;
    }

    @Override
    public void onBindViewHolder(final RecyclerView.ViewHolder viewHolder, final int position) {
        if (viewHolder == null) {
            return;
        }
        final RecordViewHolder recordViewHolder;
        recordViewHolder = ((RecordViewHolder) viewHolder);
        recordViewHolder.setData(mData.get(position), position);
        //初始化显示的时长
        recordViewHolder.mTvCurrentPlayTime.setText("0:00");
        recordViewHolder.mTvTotalPlayTime.setText(MusicUtils.makeTimeString(mContext, mData.get(position).getDuration() / 1000));
        //item点击，弹出对话框
        recordViewHolder.mContentView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                onItemClickListener.onItemClick(recordViewHolder.getAdapterPosition());
            }
        });
        //播放按钮的点击
        recordViewHolder.mIvPlay.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
//                if (mCurrentAdapterPosition != recordViewHolder.getAdapterPosition()) {
//                    //点击不是同一个条目的时候
//                    PLAY_STATUS = PlayStatus.PAUSE;
//                    mCurrentAdapterPosition = recordViewHolder.getAdapterPosition();
//                }
                switch (PLAY_STATUS) {
                    case PLAYING://正在播放
                        onPlayBackListener.onPausePlayBack();//暂停
                        changePlayState(recordViewHolder.mIvPlay, PlayStatus.PAUSE);
                        break;
                    case PAUSE://暂停
                        onPlayBackListener.onStartPlayBack(mData.get(position).getMixerFilePath());
                        changePlayState(recordViewHolder.mIvPlay, PlayStatus.PLAYING);
                        break;
                }
            }
        });
        //删除按钮的点击
        recordViewHolder.mDeleteView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                new TipsDialog(mContext, "提示", "确定删除该录音？", "确定", "取消") {
                    @Override
                    protected void OnClickNegativeButton() {
                        this.dismiss();
                    }

                    @Override
                    protected boolean OnClickPositiveButton() {
                        //删除
                        try {
                            dao.delete(mData.get(position));
                            mData.remove(mData.get(position));
                            notifyItemRemoved(recordViewHolder.getAdapterPosition());
                            this.dismiss();
                        } catch (SQLException e) {
                            e.printStackTrace();
                        }
                        return true;
                    }

                }.show();
            }
        });
//        viewHolder.itemView.setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View v) {
//                //跳转到另外一个播放页面
//                for (RecordModel model : mData) {
//                    //我的录音都是自己的头像
//                    model.setHead(XYJApplication.getUserInfo().getHeadPic());
//                }
//                IntentManager.getInstance().goLocalPlayActivity(mContext, mData, mPosition);
//            }
//        });
        //上传按钮
        recordViewHolder.mIvUpload.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (mData.get(position).getDuration() < 30000) {
                    ToastUtil.show("音频时长小于30秒，不允许上传");
                    return;
                }
                IntentManager.getInstance().goPublishRecordActivity(mContext, mData.get(position));
            }
        });
    }

    @Override
    public int getItemViewType(int position) {
        return position;
    }

    @Override
    public int getItemCount() {
        return mData.size();
    }


    public enum PlayStatus {
        PLAYING, PAUSE, STOP, UNKNOW
    }

    /**
     * 播放按钮 回调接口
     */
    public interface OnPlayBackListener {
        void onStartPlayBack(String filePath);

        void onPausePlayBack();
    }

    /**
     * 条目点击 回调接口
     */
    public interface OnItemClickListener {
        void onItemClick(int adapterPosition);
    }

    /**
     * 我的录音ViewHolder
     */
    public class RecordViewHolder extends RecyclerView.ViewHolder {
        public LinearLayout mLlPlayArea;
        public ImageView mIvPlay;//播放按钮
        public View mVUnderline;//下划线
        public MyTextView mTvCurrentPlayTime;//当前播放时间
        public MyTextView mTvTotalPlayTime;//总的播放时间
        public SeekBar mSeekBar;//播放条
        private CircleImageView mIvHead;
        private TextView mTvName;
        private TextView mTvDate;
        private TextView mTvDuration;
        private ImageView mIvUpload;
        private TextView mTvUploaded;
        private RecordModel mRecordModel;
        private int mPosition;
        private View mContentView;//内容条目
        private View mDeleteView;//删除按钮

        public RecordViewHolder(View itemView) {
            super(itemView);
            initView(itemView);
        }

        private void initView(View itemView) {
            mIvHead = (CircleImageView) itemView.findViewById(R.id.iv_record_head);
            mTvName = (TextView) itemView.findViewById(R.id.tv_record_name);
            mTvDate = (TextView) itemView.findViewById(R.id.tv_record_date);
            mTvDuration = (TextView) itemView.findViewById(R.id.tv_record_duration);
            mIvUpload = (ImageView) itemView.findViewById(R.id.iv_record_upload);
            mTvUploaded = (TextView) itemView.findViewById(R.id.tv_record_uploaded);
            mLlPlayArea = (LinearLayout) itemView.findViewById(R.id.ll_play_area);
            mIvPlay = (ImageView) itemView.findViewById(R.id.btn_play);
            mVUnderline = itemView.findViewById(R.id.v_underline);
            mTvCurrentPlayTime = (MyTextView) itemView.findViewById(R.id.current_play_time);
            mTvTotalPlayTime = (MyTextView) itemView.findViewById(R.id.audio_duration);
            mSeekBar = (SeekBar) itemView.findViewById(R.id.seek_bar_preview);
            mContentView = itemView.findViewById(R.id.smContentView);
            mDeleteView = itemView.findViewById(R.id.smMenuView);
        }

        public void setData(RecordModel model, int position) {
            this.mRecordModel = model;
            this.mPosition = position;
            //都是自己的头像
            mIvHead.displayImage(XYJApplication.getUserInfo().getHeadPic());
            mTvName.setText(model.getName());
            mTvDate.setText(TimeUtils.timeFormat(model.getCreateTime(), "MM-dd HH:mm"));
            mTvDuration.setText(TimeUtils.timeFormat(model.getDuration(), "m分ss秒"));
            if (model.isUpload()) { //已上传
                mIvUpload.setVisibility(View.GONE);
                mTvUploaded.setVisibility(View.VISIBLE);
            } else {
                mIvUpload.setVisibility(View.VISIBLE);
                mTvUploaded.setVisibility(View.GONE);
            }
            mLlPlayArea.setVisibility(View.GONE);
            mVUnderline.setVisibility(View.GONE);
        }
    }
}
